#!/bin/bash
#
# Script to calculate the interlayer distance change for 1-2, 2-3, and 3-4
#
# OUTCAR.03 are examined so that the calculation should have been completed.
if [ ! -f "OUTCAR.03" ]; then
   echo "ERROR: File OUTCAR.03 not found, calculation incomplete!"
   exit
fi
#
# get number of atoms info
natom=`grep 'NIONS' OUTCAR.01|tail -1|awk '{print $12}'`

# get surface area info
a0=`head -2 CONTCAR|tail -1|awk '{print $1}'`
lz=`head -5 CONTCAR|tail -1|awk -v s=${a0} '{print $3*s}'`

# get coordinate of topmost layers
N=`echo ${natom}|awk '{print $1+9}'`
z1=`head -$N CONTCAR|tail -1|awk -v l=${lz} '{print $3*l}'`
N=`echo ${natom}|awk '{print $1+8}'`
z2=`head -$N CONTCAR|tail -1|awk -v l=${lz} '{print $3*l}'`
N=`echo ${natom}|awk '{print $1+7}'`
z3=`head -$N CONTCAR|tail -1|awk -v l=${lz} '{print $3*l}'`
N=`echo ${natom}|awk '{print $1+6}'`
z4=`head -$N CONTCAR|tail -1|awk -v l=${lz} '{print $3*l}'`

# get coordinates of the first two layers, which are fixed
z0=`head -10 CONTCAR|tail -1|awk -v l=${lz} '{print $3*l}'`
zz=`head -11 CONTCAR|tail -1|awk -v l=${lz} '{print $3*l}'`
d0=`echo ${zz} ${z0}|awk '{print $1-$2}'`
d12=`echo ${z1} ${z2}|awk '{print $1-$2}'`	
d23=`echo ${z2} ${z3}|awk '{print $1-$2}'`	
d34=`echo ${z3} ${z4}|awk '{print $1-$2}'`	

# get the relative distance change
dd12=`echo ${d12} ${d0}|awk '{print ($1-$2)/$2*100}'`
dd23=`echo ${d23} ${d0}|awk '{print ($1-$2)/$2*100}'`
dd34=`echo ${d34} ${d0}|awk '{print ($1-$2)/$2*100}'`

# get energy difference between ideal surface and bulk material
Eunrel=`grep 'free  energy' OUTCAR.01|tail -1|awk '{print $5}'`
DelE=`echo ${Eunrel} ${E0} ${natom}|awk '{print $1 - $2*$3}'`

# Output info
echo ""
echo "The interlayer distance for ideal bulk : ${d0} Angstrom"
echo "The interlayer distance change for 1-2 : ${dd12}%"
echo "The interlayer distance change for 2-3 : ${dd23}%"
echo "The interlayer distance change for 3-4 : ${dd34}%"
echo ""
exit 0
